const mongoose = require("../db");
const Schema = mongoose.Schema;

const ticketSchema = new Schema({
  ticketId: { type: String, unique: true, required: true },
  customerId: { type: mongoose.Schema.Types.ObjectId, ref: 'Customer', required: true },
  title: { type: String, required: true },
  description: { type: String, required: true },
  priority: { 
    type: String, 
    enum: ['低', '中', '高', '紧急'], 
    default: '中' 
  },
  status: { 
    type: String, 
    enum: ['待处理', '处理中', '待客户确认', '已解决', '已关闭'], 
    default: '待处理' 
  },
  assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
  category: { 
    type: String, 
    enum: ['技术支持', '售后服务', '投诉建议', '其他'], 
    default: '其他' 
  },
  createTime: { type: Date, default: Date.now },
  resolveTime: { type: Date }
});

// 创建索引
ticketSchema.index({ ticketId: 1 });
ticketSchema.index({ customerId: 1 });
ticketSchema.index({ assignedTo: 1 });
ticketSchema.index({ status: 1 });
ticketSchema.index({ priority: 1 });
ticketSchema.index({ category: 1 });
ticketSchema.index({ createTime: -1 });

// 自动设置解决时间
ticketSchema.pre('save', function(next) {
  if (this.isModified('status') && (this.status === '已解决' || this.status === '已关闭')) {
    if (!this.resolveTime) {
      this.resolveTime = new Date();
    }
  }
  next();
});

ticketSchema.pre('findOneAndUpdate', function(next) {
  const update = this.getUpdate();
  if (update.status && (update.status === '已解决' || update.status === '已关闭')) {
    if (!update.resolveTime) {
      this.set({ resolveTime: new Date() });
    }
  }
  next();
});

module.exports = mongoose.model("Ticket", ticketSchema);